/*
 * Copyright (C) 2008 Universidade Federal de Campina Grande
 *  
 * This file is part of OurGrid. 
 *
 * OurGrid is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) 
 * any later version. 
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * for more details. 
 * 
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.ourgrid.peer.ui.async.gui;

import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

import org.ourgrid.common.ui.InputFieldsUI;
import org.ourgrid.common.util.StringUtil;
import org.ourgrid.peer.PeerConfiguration;
import org.ourgrid.peer.ui.async.client.PeerAsyncInitializer;
import org.ourgrid.peer.ui.async.model.PeerAsyncUIModel;

import br.edu.ufcg.lsd.commune.container.ContainerUtils;

/**
 * Represents a panel where it is possible to define the Discovery Service
 * settings, like: user name and server.
 */
public class DiscoveryServiceSettingsPanel extends javax.swing.JPanel implements InputFieldsUI {

	private static final long serialVersionUID = 1L;
	private PeerAsyncUIModel model;


	/** Creates new form DiscoveryServiceSettingsPanel */
    public DiscoveryServiceSettingsPanel(PeerAsyncUIModel model) {
    	this.model = model;
        initComponents();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        joinCommunityCheckBox = new javax.swing.JCheckBox();
        testConnButton = new javax.swing.JButton();
        
        jScrollPane = new javax.swing.JScrollPane();
        jPanel1 = new javax.swing.JPanel();
        
        dsURLLabel = new javax.swing.JLabel();
        urlList = new javax.swing.JList();
        addURLButton = new javax.swing.JButton();
        removeURLButton = new javax.swing.JButton();
        urlListModel = new DefaultListModel();
        urlList.setModel(urlListModel);

        joinCommunityCheckBox.setText("Join community?");

        dsURLLabel.setText("Discovery Service addresses:");

        jScrollPane.setViewportView(urlList);

        addURLButton.setText("Add DS");
        removeURLButton.setText("Remove DS");
        
        removeURLButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeURLActionPerformed();
            }
        });
        
        addURLButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addURLActionPerformed();
            }
        });

        
        testConnButton.setText("Test connection");
        testConnButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				testDiscoveryServiceConnection();			
			}
        	
        });
        
        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(joinCommunityCheckBox)
                    .add(dsURLLabel)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jScrollPane, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 290, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(removeURLButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(addURLButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(testConnButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap(39, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(joinCommunityCheckBox)
                .add(12, 12, 12)
                .add(dsURLLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(addURLButton)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(removeURLButton)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(testConnButton))
                    .add(jScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 175, Short.MAX_VALUE))
                .addContainerGap())
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        
        initFields();
    }// </editor-fold>//GEN-END:initComponents
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane;
    private javax.swing.JCheckBox joinCommunityCheckBox;
    private javax.swing.JLabel dsURLLabel;
    private javax.swing.JButton testConnButton;
	private javax.swing.JList urlList;
	private javax.swing.JButton addURLButton;
	private javax.swing.JButton removeURLButton;
	private DefaultListModel urlListModel;
    // End of variables declaration//GEN-END:variables

    /**
     * Disable the editable components of this panel.
     */
    public void disableFieldEdition() {
    	joinCommunityCheckBox.setEnabled(false);
		testConnButton.setEnabled(false);
	}
    
	/**
	 * Enable the editable components of this panel.
	 */
    public void enableFieldEdition() {
    	joinCommunityCheckBox.setEnabled(true);
		testConnButton.setEnabled(true);
	}
    
    /**
     * Tests the NodeWiz connection, using the values setted.
     */
    private void testDiscoveryServiceConnection() {
    	Cursor hourglassCursor = new Cursor(Cursor.WAIT_CURSOR);
    	setCursor(hourglassCursor);
    	
    	Object[] selectedValue = urlList.getSelectedValues();
		
		if (selectedValue == null) {
			JOptionPane.showMessageDialog(null, "No discovery service was selected.",
					"Discovery Service connection", JOptionPane.ERROR_MESSAGE);
		}
		
		for (int i = 0; i < selectedValue.length; i++) {
			
			String address = (String) selectedValue[i];
			
			String[] splitAddress = StringUtil.splitAddress((String)selectedValue[i]);
			String userName = splitAddress[0];
			
			boolean connected = true;
			
			if (splitAddress.length != 2) {
				connected = false;
			}  else {
				String serverName = splitAddress[1];
				connected = PeerAsyncInitializer.getInstance().getComponentClient().
				testConnectionWithDiscoveryService(userName, serverName);
			}
			
			if (!connected) {
				JOptionPane.showMessageDialog(null, "Discovery Service : " + address + " could not be contacted.",
						"Discovery Service connection", JOptionPane.ERROR_MESSAGE);
			} else {
				JOptionPane.showMessageDialog(null, "Discovery Service : " + address + " successfully contacted.",
						"Discovery Service connection", JOptionPane.INFORMATION_MESSAGE);
			}
		}
		
		Cursor normalCursor = new Cursor(Cursor.DEFAULT_CURSOR);
		setCursor(normalCursor);
	}
    
    
	/**
	 * Save the basic properties of the peer.
	 */
    public void saveProperties() {
    	model.setProperty(PeerConfiguration.PROP_JOIN_COMMUNITY, 
    			joinCommunityCheckBox.isSelected() ? "yes" : "no");
    	
    	
		List<String> urlList = new ArrayList<String>();
		for (int i = 0; i < urlListModel.getSize(); i++) {
			urlList.add((String) urlListModel.getElementAt(i));
		}
		
		model.setProperty(PeerConfiguration.PROP_DS_NETWORK, 
				ContainerUtils.getStringListProperty(urlList));
	}

	/**
	 * Initializes the textFields.
	 */
	public void initFields() {
    	joinCommunityCheckBox.setSelected(model.getProperty(
    			PeerConfiguration.PROP_JOIN_COMMUNITY).equals("yes"));
    	
		urlListModel.clear();
		
		String dsUrlStr = model.getProperty(PeerConfiguration.PROP_DS_NETWORK);		
		List<String> dsUrls = ContainerUtils.parseStringList(dsUrlStr);
		for (String dsUrl : dsUrls) {
			urlListModel.addElement(dsUrl);
		}
	}

	/**
	 * Save the values of the field inputs.
	 */
	public void saveFieldInputs() throws IOException {
		saveProperties();
	}

	/**
	 * Disable the editable components of this panel.
	 */
	public void disableInput() {
		disableFieldEdition();
		
	}

	/**
	 * Enable the editable components of this panel.
	 */
	public void enableInput() {
		enableFieldEdition();
		
	}
	
    protected void addURLActionPerformed() {
		String urlToAdd = JOptionPane.showInputDialog(this, "DS Address to be added:", "DS Address", JOptionPane.PLAIN_MESSAGE);
		if (urlToAdd != null && urlToAdd.length() > 0) {
			urlListModel.addElement(urlToAdd);
		}
	}

	protected void removeURLActionPerformed() {
    	for (Object selectedURL : urlList.getSelectedValues()) {
    		urlListModel.removeElement(selectedURL);
    	}
	}

    
}
